let newsList = []; // 存储所有新闻数据
let typesList = []; // 存储所有分类数据

// 初始化页面
async function initNewsManagement() {
    // 同时加载新闻和分类数据
    await Promise.all([loadNewsData(), loadTypesData()]);
    // 渲染新闻表格和分类下拉框
    renderTypeSelects();
    // 绑定事件
    bindEvents();
}


// 绑定编辑/删除按钮事件
document.querySelectorAll('.edit-btn').forEach(btn => {
    btn.addEventListener('click', () => openEditModal(btn.dataset.id));
});
document.querySelectorAll('.delete-btn').forEach(btn => {
    btn.addEventListener('click', () => deleteNews(btn.dataset.id));
});

// 渲染分类下拉框（筛选和表单中）
function renderTypeSelects() {
    const typeFilter = document.getElementById('type-select');
    const newsTypeForm = document.getElementById('news-type');

    // 清空现有选项（保留全部分类）
    typeFilter.innerHTML = '<option value="all">全部分类</option>';
    newsTypeForm.innerHTML = '';

    typesList.forEach(type => {
        typeFilter.innerHTML += `<option value="${type.name}">${type.name}</option>`;
        newsTypeForm.innerHTML += `<option value="${type.name}">${type.name}</option>`;
    });
}

// 绑定页面所有事件
function bindEvents() {

    // 3. 新闻表单提交
    document.getElementById('news-form').addEventListener('submit', saveNews);

    // 4. 搜索功能
    document.getElementById('search-btn').addEventListener('click', handleSearch);
    document.getElementById('news-search').addEventListener('keydown', (e) => {
        if (e.key === 'Enter') handleSearch();
    });

    // 5. 分类筛选
    document.getElementById('type-select').addEventListener('change', handleTypeFilter);
}

// 打开添加新闻模态框
function openAddModal() {

}

// 打开编辑新闻模态框
function openEditModal(newsId) {
    // const news = newsList.find(item => item.id.toString() === newsId);
    // if (!news) return;
    //
    document.getElementById('modal-title').textContent = '编辑新闻';
    document.getElementById('news-id').value = news.id;
    document.getElementById('news-title').value = news.title;
    document.getElementById('news-type').value = news.type;
    document.getElementById('news-author').value = news.author;
    document.getElementById('news-image').value = news.image || '';
    document.getElementById('news-content').value = news.content;
    document.getElementById('news-status').value = news.status;
    document.getElementById('news-modal').classList.remove('hidden');
}

// 关闭模态框
function closeModal() {
    document.getElementById('news-modal').classList.add('hidden');
}

// 保存新闻（新增/编辑）
function saveNews(e) {
    e.preventDefault();

    const newsId = document.getElementById('news-id').value;
    const newsData = {
        title: document.getElementById('news-title').value,
        type: document.getElementById('news-type').value,
        author: document.getElementById('news-author').value,
        image: document.getElementById('news-image').value,
        content: document.getElementById('news-content').value,
        status: document.getElementById('news-status').value,
        time: new Date().toLocaleDateString('zh-CN') // 取当前日期
    };

    if (newsId) {
        // 编辑新闻
        const index = newsList.findIndex(item => item.id.toString() === newsId);
        newsList[index] = {...newsList[index], ...newsData};
        alert('新闻编辑成功！');
    } else {
        // 新增新闻
        const newId = Math.max(...newsList.map(item => item.id), 0) + 1;
        newsList.unshift({id: newId, ...newsData});
        alert('新闻添加成功！');
    }

    // 重新渲染表格并关闭模态框
    renderNewsTable(newsList);
    closeModal();
}

// 搜索新闻
function handleSearch() {
    const keyword = document.getElementById('news-search').value.trim().toLowerCase();
    const filtered = newsList.filter(news =>
        news.title.toLowerCase().includes(keyword) ||
        news.content.toLowerCase().includes(keyword)
    );
    renderNewsTable(filtered);
}

// 分类筛选
function handleTypeFilter() {
    const type = document.getElementById('type-select').value;
    if (type === 'all') {
        renderNewsTable(newsList);
        return;
    }
    const filtered = newsList.filter(news => news.type === type);
    renderNewsTable(filtered);
}

// 页面加载初始化
window.onload = initNewsManagement;
